<template>
  <span class="code active" @click="startTimer" v-if="num === 60"
    >获取验证码</span
  >
  <span class="code" v-else>{{ num }}s</span>
</template>

<script>
import { onBeforeUnmount, ref } from "vue";
import { message } from "ant-design-vue";
import { fetchCode } from "/src/api/index.js";

export default {
  props: {
    phone: {
      type: [Number, String],
      default: "",
    },
  },
  setup(props) {
    const num = ref(60);
    const timer = ref(null);
    onBeforeUnmount(() => {
      if (timer.value) clearTimeout(timer.value);
    });
    const startTimer = () => {
      setTimeout(async () => {
        if (num.value === 60) {
          if (/^1\d{10}$/g.test(props.phone)) {
            await fetchCode(props.phone);
            message.info("验证码已发送，请查收");
          } else {
            return message.warning("请输入正确的手机号码");
          }
        }
        if (num.value <= 0) {
          return (num.value = 60);
        }
        num.value -= 1;
        timer.value = setTimeout(() => {
          startTimer();
        }, 1000);
      }, 100);
    };
    return {
      num,
      startTimer,
    };
  },
};
</script>

<style lang="less" scoped>
.code {
  cursor: pointer;
}
.active {
  color: #fe246c;
}
</style>
